<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员控制面板 - 教室上课签到系统</title>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js" crossorigin="anonymous"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .logout-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }
        .logout-btn:hover {
            background-color: #d32f2f;
        }
        .layout-config {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        input[type="number"] {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 100px;
        }
        .btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .cinema-layout {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 20px;
        }
        .screen {
            background-color: #333;
            color: white;
            padding: 10px 200px;
            text-align: center;
            margin-bottom: 30px;
            border-radius: 4px;
        }
        .seat-row {
            display: flex;
            margin-bottom: 10px;
        }
        .row-label {
            width: 60px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            font-weight: bold;
            color: #555;
        }
        .seat {
            width: 40px;
            height: 40px;
            margin: 5px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            position: relative;
        }
        .seat.available {
            background-color: #4CAF50;
            color: white;
        }
        .seat.unavailable {
            background-color: #444444;
            color: white;
        }
        .seat.single-selected {
            background-color: #2196F3;
            color: white;
        }
        .seat.multi-selected {
            background-color: #f44336;
            color: white;
        }
        .seat:hover {
            opacity: 0.8;
        }
        .tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            margin-bottom: 10px;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            white-space: pre-line;
            width: 200px;
            max-width: 250px;
            z-index: 1000;
            pointer-events: none;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.2s, visibility 0.2s;
        }
        .tooltip::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: rgba(0, 0, 0, 0.8) transparent transparent transparent;
        }
        .legend {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            margin: 0 15px;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>管理员控制面板</h1>
            <a href="{{ url_for('logout') }}" class="logout-btn">退出登录</a>
        </div>
        
        <div class="layout-config">
            <h2>座位布局设置</h2>
            <form id="layout-form">
                <div class="form-group">
                    <label for="row-count">行数:</label>
                    <input type="number" id="row-count" name="row-count" min="1" max="20" value="{{ layout.row_count }}">
                </div>
                <div class="form-group">
                    <label for="column-count">列数:</label>
                    <input type="number" id="column-count" name="column-count" min="1" max="30" value="{{ layout.column_count }}">
                </div>
                <button type="submit" class="btn">更新布局</button>
                </form>
            </div>
            
            <div class="form-group">
                <button id="clear-selections-btn" class="btn btn-danger">清空所有用户选座数据</button>
                <button id="export-selections-btn" class="btn btn-success">导出选座</button>
                <button id="init-db-btn" class="btn btn-warning">初始化数据库</button>
            </div>
        
        <div class="cinema-layout">
            <div class="screen">屏幕</div>
            <div id="seats-container">
                {% for row in range(1, layout.row_count + 1) %}
                <div class="seat-row">
                    <div class="row-label">第{{ row }}排</div>
                    {% for seat in seat_data %}
                    {% if seat.row == row %}
                    <div class="seat {% if not seat.is_available %}unavailable{% elif seat.selection_count == 1 %}single-selected{% elif seat.selection_count > 1 %}multi-selected{% else %}available{% endif %}"
                         data-seat-id="{{ seat.id }}"
                         data-row="{{ seat.row }}"
                         data-number="{{ seat.number }}">
                        {% if seat.selection_count > 0 %}
                            {% if seat.user_list and seat.user_list|length > 0 %}
                                {{ seat.user_list[0].nick }}
                            {% endif %}
                        {% else %}
                            {{ seat.number }}
                        {% endif %}
                        <div class="tooltip">
                            {% if not seat.is_available %}
                            此座位不可选
                            {% elif seat.selection_count > 0 %}
                            已有 {{ seat.selection_count }} 人选择此座位
                            {% if seat.user_list and seat.user_list|length > 0 %}
                            
选择人员：
                            {% for user in seat.user_list %}
                            {{ loop.index }}. {{ user.username }} ({{ user.nick }})
                            {% endfor %}
                            {% endif %}
                            {% else %}
                            座位 {{ seat.number }} - 可选
                            {% endif %}
                        </div>
                    </div>
                    {% endif %}
                    {% endfor %}
                </div>
                {% endfor %}
            </div>
            
            <div class="legend">
                <div class="legend-item">
                    <div class="legend-color available"></div>
                    <span>可选座位</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color unavailable"></div>
                    <span>不可选座位</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color single-selected"></div>
                    <span>1人选择的座位</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color multi-selected"></div>
                    <span>2人及以上选择的座位</span>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 初始化Socket.io，连接到正确的端口
        const socket = io(window.location.origin);
        
        // 页面加载完成后初始化tooltip
        document.addEventListener('DOMContentLoaded', () => {
            // 获取所有座位
            document.querySelectorAll('.seat').forEach(seat => {
                const seatId = seat.getAttribute('data-seat-id');
                const isAvailable = seat.classList.contains('available');
                const isSingleSelected = seat.classList.contains('single-selected');
                const isMultiSelected = seat.classList.contains('multi-selected');
                
                // 更新tooltip内容
                const tooltip = seat.querySelector('.tooltip');
                if (tooltip) {
                    // 获取座位数据
                    fetch(`/api/seat/${seatId}/info`)
                        .then(response => response.json())
                        .then(data => {
                            if (data && data.is_available !== undefined) {
                                if (!data.is_available) {
                                    tooltip.textContent = '此座位不可选';
                                } else if (data.selection_count > 0) {
                                    let tooltipContent = `已有 ${data.selection_count} 人选择此座位`;
                                    if (data.user_list && data.user_list.length > 0) {
                                        tooltipContent += '\n选择人员：';
                                        data.user_list.forEach((user, index) => {
                                            tooltipContent += `\n${index + 1}. ${user.username} (${user.nick})`;
                                        });
                                        
                                        // 如果有用户选择，显示第一个用户的昵称
                                        if (data.selection_count > 0) {
                                            const userName = data.user_list[0].nick || data.user_list[0].username;
                                            // 清空座位内容但保留tooltip
                                            while (seat.firstChild) {
                                                if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                                                    break;
                                                }
                                                seat.removeChild(seat.firstChild);
                                            }
                                            // 添加用户昵称
                                            const nameElement = document.createElement('div');
                                            nameElement.textContent = userName;
                                            nameElement.style.fontSize = '10px';
                                            nameElement.style.textAlign = 'center';
                                            nameElement.style.padding = '2px';
                                            // 确保tooltip在最后
                                            seat.insertBefore(nameElement, tooltip);
                                        }
                                    }
                                    tooltip.textContent = tooltipContent;
                                } else {
                                    tooltip.textContent = '座位 ' + seat.getAttribute('data-number') + ' - 可选';
                                }
                            }
                        })
                        .catch(error => {
                            console.error('获取座位信息失败:', error);
                            // 默认显示
                            if (!isAvailable) {
                                tooltip.textContent = '此座位不可选';
                            } else {
                                tooltip.textContent = '座位 ' + seat.getAttribute('data-number') + ' - 可选';
                            }
                        });
                }
            });
        });
        
        // 更新座位状态和处理tooltip显示
        document.querySelectorAll('.seat').forEach(seat => {
            // 点击事件处理座位状态更新
            seat.addEventListener('click', () => {
                const seatId = seat.getAttribute('data-seat-id');
                const isAvailable = seat.classList.contains('available');
                const isSingleSelected = seat.classList.contains('single-selected');
                const isMultiSelected = seat.classList.contains('multi-selected');
                
                // 判断最终目标状态
                let targetIsAvailable = !isAvailable;
                
                // 如果座位有人选择，点击后应该切换为不可用
                if (isSingleSelected || isMultiSelected) {
                    targetIsAvailable = false;
                }
                
                // 更新UI
                seat.classList.toggle('available', targetIsAvailable);
                seat.classList.toggle('unavailable', !targetIsAvailable);
                
                // 如果切换为不可用，移除所有其他状态类，确保显示为灰黑色
                if (!targetIsAvailable) {
                    seat.classList.remove('single-selected', 'multi-selected');
                    // 更新tooltip内容
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.textContent = '此座位不可选';
                    }
                    
                    // 更新座位显示为座位号
                    const seatNumber = seat.getAttribute('data-number');
                    // 清空座位内容但保留tooltip
                    while (seat.firstChild) {
                        if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                            break;
                        }
                        seat.removeChild(seat.firstChild);
                    }
                    // 添加座位号
                    const numberElement = document.createElement('div');
                    numberElement.textContent = seatNumber;
                    numberElement.style.fontSize = '12px';
                    numberElement.style.textAlign = 'center';
                    // 确保tooltip在最后
                    if (tooltip) {
                        seat.insertBefore(numberElement, tooltip);
                    } else {
                        seat.appendChild(numberElement);
                    }
                }
                // 如果切换为可用
                else {
                    // 更新tooltip内容
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.textContent = '座位 ' + seat.getAttribute('data-number') + ' - 可选';
                    }
                    
                    // 恢复显示座位号
                    const seatNumber = seat.getAttribute('data-number');
                    // 清空座位内容但保留tooltip
                    while (seat.firstChild) {
                        if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                            break;
                        }
                        seat.removeChild(seat.firstChild);
                    }
                    // 添加座位号
                    const numberElement = document.createElement('div');
                    numberElement.textContent = seatNumber;
                    numberElement.style.fontSize = '12px';
                    numberElement.style.textAlign = 'center';
                    // 确保tooltip在最后
                    if (tooltip) {
                        seat.insertBefore(numberElement, tooltip);
                    } else {
                        seat.appendChild(numberElement);
                    }
                }
                    
                    // 发送更新到服务器
                    socket.emit('update_seat_status', {
                        seat_id: seatId,
                        is_available: targetIsAvailable
                    });
                });
                
                // 鼠标悬停显示tooltip
                seat.addEventListener('mouseenter', () => {
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.style.opacity = '1';
                        tooltip.style.visibility = 'visible';
                    }
                });
                
                // 鼠标离开隐藏tooltip
                seat.addEventListener('mouseleave', () => {
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.style.opacity = '0';
                        tooltip.style.visibility = 'hidden';
                    }
                });
            });
        
        // 监听座位状态更新
        socket.on('seat_status_updated', data => {
            const seat = document.querySelector(`.seat[data-seat-id="${data.seat_id}"]`);
            if (seat) {
                seat.classList.toggle('available', data.is_available);
                seat.classList.toggle('unavailable', !data.is_available);
                // 移除多人选座状态，如果座位不可用
                if (!data.is_available) {
                    seat.classList.remove('multi-selected');
                    // 更新tooltip内容
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.textContent = '此座位不可选';
                    }
                }
            }
        });
        
        // 监听座位选择更新
        socket.on('seat_selected', data => {
            const seat = document.querySelector(`.seat[data-seat-id="${data.seat_id}"]`);
            if (seat) {
                // 根据选座人数更新座位样式
                seat.classList.remove('available', 'single-selected', 'multi-selected');
                
                // 根据选座人数设置不同的样式类
                if (data.selection_count === 1) {
                    seat.classList.add('single-selected');
                } else if(data.selection_count > 1) {
                    seat.classList.add('multi-selected');
                }
                
                // 如果有用户选择，显示第一个用户的昵称
                if (data.selection_count > 0 && data.user_list && data.user_list.length > 0) {
                    const userName = data.user_list[0].nick || data.user_list[0].username;
                    // 清空座位内容但保留tooltip
                    while (seat.firstChild) {
                        if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                            break;
                        }
                        seat.removeChild(seat.firstChild);
                    }
                    // 添加用户昵称
                    const nameElement = document.createElement('div');
                    nameElement.textContent = userName;
                    nameElement.style.fontSize = '10px';
                    nameElement.style.textAlign = 'center';
                    nameElement.style.padding = '2px';
                    // 确保tooltip在最后
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        seat.insertBefore(nameElement, tooltip);
                    } else {
                        seat.appendChild(nameElement);
                    }
                }
                
                // 更新tooltip内容
                const tooltip = seat.querySelector('.tooltip');
                if (tooltip) {
                    // 设置tooltip内容
                    let tooltipContent = `已有 ${data.selection_count} 人选择此座位`;
                    if (data.user_list && data.user_list.length > 0) {
                        tooltipContent += '\n选择人员：';
                        data.user_list.forEach((user, index) => {
                            tooltipContent += `\n${index + 1}. ${user.username} (${user.nick})`;
                        });
                    }
                    tooltip.textContent = tooltipContent;
                }
            }
        });
        
        // 监听座位取消选择更新
        socket.on('seat_deselected', data => {
            const seat = document.querySelector(`.seat[data-seat-id="${data.seat_id}"]`);
            if (seat && !seat.classList.contains('unavailable')) {
                if (data.selection_count === 0) {
                    // 如果没有人选择了，恢复为可用状态
                    seat.classList.remove('single-selected', 'multi-selected');
                    if (!seat.classList.contains('unavailable')) {
                        seat.classList.add('available');
                    }
                    // 更新tooltip内容
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        tooltip.textContent = '座位 ' + seat.getAttribute('data-number') + ' - 可选';
                    }
                    
                    // 恢复显示座位号
                    const seatNumber = seat.getAttribute('data-number');
                    // 清空座位内容但保留tooltip
                    while (seat.firstChild) {
                        if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                            break;
                        }
                        seat.removeChild(seat.firstChild);
                    }
                    // 添加座位号
                    const numberElement = document.createElement('div');
                    numberElement.textContent = seatNumber;
                    numberElement.style.fontSize = '12px';
                    numberElement.style.textAlign = 'center';
                    // 确保tooltip在最后
                    if (tooltip) {
                        seat.insertBefore(numberElement, tooltip);
                    } else {
                        seat.appendChild(numberElement);
                    }
                } else {
                    // 更新tooltip内容
                    const tooltip = seat.querySelector('.tooltip');
                    if (tooltip) {
                        let tooltipContent = `已有 ${data.selection_count} 人选择此座位`;
                        if (data.user_list && data.user_list.length > 0) {
                            tooltipContent += '\n选择人员：';
                            data.user_list.forEach((user, index) => {
                                tooltipContent += `\n${index + 1}. ${user.username} (${user.nick})`;
                            });
                        }
                        tooltip.textContent = tooltipContent;
                    }
                    
                    // 根据选座人数更新座位样式
                    seat.classList.remove('available', 'single-selected', 'multi-selected');
                    if (data.selection_count === 1) {
                        seat.classList.add('single-selected');
                    } else {
                        seat.classList.add('multi-selected');
                    }
                    
                    // 如果有用户选择，显示第一个用户的昵称
                    if (data.selection_count > 0 && data.user_list && data.user_list.length > 0) {
                        const userName = data.user_list[0].nick || data.user_list[0].username;
                        // 清空座位内容但保留tooltip
                        while (seat.firstChild) {
                            if (seat.firstChild.classList && seat.firstChild.classList.contains('tooltip')) {
                                break;
                            }
                            seat.removeChild(seat.firstChild);
                        }
                        // 添加用户昵称
                        const nameElement = document.createElement('div');
                        nameElement.textContent = userName;
                        nameElement.style.fontSize = '10px';
                        nameElement.style.textAlign = 'center';
                        nameElement.style.padding = '2px';
                        // 确保tooltip在最后
                        const tooltip = seat.querySelector('.tooltip');
                        if (tooltip) {
                            seat.insertBefore(nameElement, tooltip);
                        } else {
                            seat.appendChild(nameElement);
                        }
                    }
                }
            }
        });
        
        // 处理布局更新
        document.getElementById('layout-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const rowCount = parseInt(document.getElementById('row-count').value);
            const columnCount = parseInt(document.getElementById('column-count').value);
            
            // 先发送请求清空所有用户选座数据
            fetch('/api/clear_all_selections', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                // 无论清空选座数据是否成功，都继续更新布局
                // 发送布局更新请求
                return fetch('/api/layout/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        row_count: rowCount,
                        column_count: columnCount
                    })
                });
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 刷新页面以显示新布局
                    location.reload();
                }
            });
        });
        
        // 清空所有用户选座数据按钮点击事件
        document.getElementById('clear-selections-btn').addEventListener('click', () => {
            if (confirm('确定要清空所有一般用户的选座数据吗？此操作不可恢复。')) {
                // 发送请求清空所有用户选座数据
                fetch('/api/clear_all_selections', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        //alert(data.message);
                        // 刷新页面以显示最新状态
                        location.reload();
                    } else {
                        alert('操作失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('清空选座数据失败:', error);
                    alert('操作失败，请稍后重试。');
                });
            }
        });

        // 初始化数据库按钮点击事件
        document.getElementById('init-db-btn').addEventListener('click', () => {
            if (confirm('确定要初始化数据库吗？此操作将清空所有数据并重新从文件载入管理员和一般用户。')) {
                // 发送请求初始化数据库
                fetch('/api/init_database', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert(data.message);
                        // 刷新页面以显示最新状态
                        location.reload();
                    } else {
                        alert('操作失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('初始化数据库失败:', error);
                    alert('操作失败，请稍后重试。');
                });
            }
        });

        // 导出选座按钮点击事件
        document.getElementById('export-selections-btn').addEventListener('click', () => {
            // 直接跳转到服务器端生成GBK编码的CSV文件的API端点
            window.location.href = '/api/download_attendance';
        });
        
        // 监听布局更新
        socket.on('layout_updated', data => {
            // 刷新页面以显示新布局
            location.reload();
        });
    </script>
</body>
</html>